<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="120px">
      <el-form-item label="充电规则名称" prop="schemeName">
        <el-input
          v-model="queryParams.schemeName"
          placeholder="请输入充电规则名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="计费类型" prop="type">
        <el-select v-model="queryParams.type" placeholder="请选择计费类型" clearable>
          <el-option
            v-for="dict in dict.type.charging_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:scheme:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:scheme:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:scheme:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:scheme:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="schemeList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
<!--      <el-table-column label="充电规则ID" align="center" prop="chargingSchemeId" />-->
      <el-table-column label="充电规则名称" width="200"  align="center" prop="schemeName" />
      <el-table-column label="计费类型" align="center" prop="type">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.charging_type" :value="scope.row.type"/>
        </template>
      </el-table-column>
      <el-table-column label="最大充电时长" align="center" prop="maxChargingTime" />
      <el-table-column label="电价成本" align="center" prop="eleCost" />
      <el-table-column label="起充价格" align="center" prop="startPrice" />
      <el-table-column label="按度充电价格" align="center" prop="degreePrice" />
      <el-table-column label="是否最大功率" align="center" prop="isMaxPower">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.yes_no" :value="scope.row.isMaxPower"/>
        </template>
      </el-table-column>
      <el-table-column label="是否小时计费" align="center" prop="isHourCharging">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.yes_no" :value="scope.row.isHourCharging"/>
        </template>
      </el-table-column>
      <el-table-column label="是否后付款" align="center" prop="isPayLater">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.yes_no" :value="scope.row.isPayLater"/>
        </template>
      </el-table-column>
<!--      <el-table-column label="方案详细" align="center" prop="schemeDetailed" />-->
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:scheme:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:scheme:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改充电规则对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1000px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="充电规则名称" prop="schemeName">
          <el-input v-model="form.schemeName" placeholder="请输入充电规则名称" />
        </el-form-item>
        <el-form-item label="计费类型" prop="type">
          <el-select v-model="form.type" placeholder="请选择计费类型">
            <el-option
              v-for="dict in dict.type.charging_type"
              :key="dict.value"
              :label="dict.label"
              :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item v-if="form.type == 1" label="最大充电时长" prop="maxChargingTime">
          <el-input v-model="form.maxChargingTime" placeholder="请输入最大充电时长" />
        </el-form-item>
        <el-form-item label="电价成本" prop="eleCost">
          <el-input v-model="form.eleCost" placeholder="请输入电价成本" />
        </el-form-item>
        <el-form-item  v-if="form.type == 1" label="起充价格" prop="startPrice">
          <el-input v-model="form.startPrice" placeholder="请输入起充价格" />
        </el-form-item>
        <el-form-item  v-if="form.type == 1" label="按度充电价格" prop="degreePrice">
          <el-input v-model="form.degreePrice" placeholder="请输入按度充电价格" />
        </el-form-item>
        <el-form-item  v-if="form.type == 1" label="是否最大功率" prop="isMaxPower">
          <el-select v-model="form.isMaxPower" placeholder="请选择是否最大功率">
            <el-option
              v-for="dict in dict.type.yes_no"
              :key="dict.value"
              :label="dict.label"
              :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="是否小时计费" prop="isHourCharging">
          <el-select v-model="form.isHourCharging" placeholder="请选择是否小时计费">
            <el-option
              v-for="dict in dict.type.yes_no"
              :key="dict.value"
              :label="dict.label"
              :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="是否后付款" prop="isPayLater">
          <el-select v-model="form.isPayLater" placeholder="请选择是否后付款">
            <el-option
              v-for="dict in dict.type.yes_no"
              :key="dict.value"
              :label="dict.label"
              :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>

<!--        <el-form-item label="方案详细" prop="schemeDetailed">-->
<!--          <el-input v-model="form.schemeDetailed" type="textarea" placeholder="请输入内容" />-->
<!--        </el-form-item>-->
        <!--分功率段价格-->
        <div v-if="form.type == 1">
          <el-form-item label="分功率段价格" />
          <el-table
            :data="chargingSchemeDetailed"
            style="width: 100%"
          >
            <el-table-column
              prop="min_power"
              label="功率小"
            >
              <template slot-scope="{row}">
                <el-input v-model="row.min_power" />
              </template>
            </el-table-column>
            <el-table-column
              prop="max_power"
              label="功率大"
            >
              <template slot-scope="{row}">
                <el-input v-model="row.max_power" />
              </template>
            </el-table-column>
            <el-table-column
              prop="ele_price"
              label="金额"
            >
              <template slot-scope="{row}">
                <el-input v-model="row.ele_price" />
              </template>
            </el-table-column>
            <el-table-column
              prop="index"
              label="排序"
              width="60"
            >
              <template slot-scope="{row}">
                <el-input v-model="row.index" />
              </template>
            </el-table-column>
            <el-table-column
              fixed="right"
              label="操作"
              width="60"
            >
              <template slot-scope="scope">
                <el-button
                  type="text"
                  size="small"
                  @click.native.prevent="deleteRow(scope.$index, chargingSchemeDetailed)"
                >
                  移除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-button type="primary" size="mini" @click="addRow(form.type, chargingSchemeDetailed)">添加规则</el-button>
        </div>
        <!--分时段按度计费-->
        <div v-if="form.type == 2">
          <!--          <el-form-item label="尖、峰、平、谷价格费率服务费" style="width:500px"/>-->
          <el-form :inline="true">
            <el-form-item label="尖电费费率">
              <el-input v-model="chargingSchemeDetailed.topCost" :rules="priceRule" placeholder="尖电费费率" />
            </el-form-item>
            <el-form-item label="尖电费服务费">
              <el-input v-model="chargingSchemeDetailed.topFees" :rules="priceRule" placeholder="尖电费服务费" />
            </el-form-item>
            <el-form-item label="尖电费价格">
              <el-input disabled :value="(Number(chargingSchemeDetailed.topCost)+Number(chargingSchemeDetailed.topFees))" placeholder="尖电费服务费" />
            </el-form-item>
          </el-form>
          <el-form :inline="true">
            <el-form-item label="峰电费费率">
              <el-input v-model="chargingSchemeDetailed.peakCost" :rules="priceRule" placeholder="峰电费费率" />
            </el-form-item>
            <el-form-item label="峰电费服务费">
              <el-input v-model="chargingSchemeDetailed.peakFees" :rules="priceRule" placeholder="峰电费服务费" />
            </el-form-item>
            <el-form-item label="峰电费价格">
              <el-input disabled :value="(Number(chargingSchemeDetailed.peakCost)+Number(chargingSchemeDetailed.peakFees))" placeholder="峰电费服务费" />
            </el-form-item>
          </el-form>
          <el-form :inline="true">
            <el-form-item label="平电费费率">
              <el-input v-model="chargingSchemeDetailed.flatCost" :rules="priceRule" placeholder="平电费费率" />
            </el-form-item>
            <el-form-item label="平电费服务费">
              <el-input v-model="chargingSchemeDetailed.flatFees" :rules="priceRule" placeholder="平电费服务费" />
            </el-form-item>
            <el-form-item label="平电费价格">
              <el-input disabled :value="(Number(chargingSchemeDetailed.flatCost)+Number(chargingSchemeDetailed.flatFees))" placeholder="平电费价格" />
            </el-form-item>
          </el-form>
          <el-form :inline="true">
            <el-form-item label="谷电费费率">
              <el-input v-model="chargingSchemeDetailed.lowCost" :rules="priceRule" placeholder="谷电费费率" />
            </el-form-item>
            <el-form-item label="谷电费服务费">
              <el-input v-model="chargingSchemeDetailed.lowFees" :rules="priceRule" placeholder="谷电费服务费" />
            </el-form-item>
            <el-form-item label="谷电费价格">
              <el-input disabled :value="(Number(chargingSchemeDetailed.lowCost)+Number(chargingSchemeDetailed.lowFees))" placeholder="谷电费价格" />
            </el-form-item>
          </el-form>

          <el-form-item label="分时段价格" />

          <el-table
            :data="chargingSchemeDetailed.detailed"
            style="width: 100%"
          >
            <el-table-column
              prop="start_time"
              label="开始时间"
            >
              <template slot-scope="{row}">
                <el-time-select
                  v-model="row.start_time"
                  :picker-options="{
                    start: '00:00',
                    step: '00:30'
                  }"
                  placeholder="选择时间"
                />
              </template>
            </el-table-column>
            <el-table-column
              prop="end_time"
              label="结束时间"
            >
              <template slot-scope="{row}">
                <el-time-select
                  v-model="row.end_time"
                  :picker-options="{
                    start: '00:00',
                    step: '00:30'
                  }"
                  placeholder="选择时间"
                />
              </template>
            </el-table-column>
            <el-table-column
              prop="end_time"
              label="选择价格"
            >
              <template slot-scope="{row}">
                <el-select v-model="row.cost" placeholder="请选择">
                  <el-option
                    v-for="costItem in costOption"
                    :key="costItem.value"
                    :label="costItem.label"
                    :value="costItem.value"
                  />
                </el-select>
              </template>
            </el-table-column>
            <el-table-column
              prop="index"
              label="排序"
              width="60"
            >
              <template slot-scope="{row}">
                <el-input v-model="row.index" />
              </template>
            </el-table-column>
            <el-table-column
              fixed="right"
              label="操作"
              width="60"
            >
              <template slot-scope="scope">
                <el-button
                  type="text"
                  size="small"
                  @click.native.prevent="deleteRow(scope.$index, chargingSchemeDetailed.detailed)"
                >
                  移除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-button type="primary" size="mini" @click="addRow(from.type, chargingSchemeDetailed.detailed)">添加规则</el-button>
        </div>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { listScheme, getScheme, delScheme, addScheme, updateScheme } from "@/api/system/scheme";

export default {
  name: "Scheme",
  dicts: ['charging_type', 'yes_no'],
  data() {
    return {
      chargingSchemeDetailed: null,
      costOption: [{ label: '尖电费价格', value: '00' }, { label: '峰电费价格', value: '01' }, { label: '平电费价格', value: '02' }, { label: '谷电费价格', value: '03' }],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 充电规则表格数据
      schemeList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        schemeName: null,
        type: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        type: [
          { required: true, message: "计费类型不能为空", trigger: "change" }
        ],
        maxChargingTime: [
          { required: true, message: "最大充电时长不能为空", trigger: "blur" }
        ],
        isMaxPower: [
          { required: true, message: "是否最大功率不能为空", trigger: "change" }
        ],
        isHourCharging: [
          { required: true, message: "是否小时计费不能为空", trigger: "change" }
        ],
        isPayLater: [
          { required: true, message: "是否后付款不能为空", trigger: "change" }
        ],
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    deleteRow(index, rows) {
      if (rows.length > 1) {
        rows.splice(index, 1)
      } else {
        this.$modal.alert('必须保留一条')
      }
    },
    addRow(type, rows) {
      if (type === 1) {
        rows.push({ min_power: '0', max_power: '0', ele_price: '0', index: '9' })
      }
      if (type === 2) {
        rows.push({ start_time: '00:00', end_time: '00:00', ele_price: '0', cost: '02', index: '9' })
      }
    },
    /** 查询充电规则列表 */
    getList() {
      this.loading = true;
      listScheme(this.queryParams).then(response => {
        this.schemeList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        chargingSchemeId: null,
        schemeName: null,
        type: null,
        maxChargingTime: null,
        eleCost: null,
        startPrice: null,
        degreePrice: null,
        isMaxPower: null,
        isHourCharging: null,
        isPayLater: null,
        roleSort: null,
        schemeDetailed: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null,
        delFlag: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.chargingSchemeId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加充电规则";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const chargingSchemeId = row.chargingSchemeId || this.ids
      getScheme(chargingSchemeId).then(response => {
        this.form = response.data;
        this.chargingSchemeDetailed = JSON.parse(response.data.schemeDetailed)
        this.open = true;
        this.title = "修改充电规则";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.type === 2) {
            for (const i in this.chargingSchemeDetailed.detailed) {
              if (this.chargingSchemeDetailed.detailed[i].cost === '00') {
                this.chargingSchemeDetailed.detailed[i].ele_price = Number(this.chargingSchemeDetailed.topCost) + Number(this.chargingSchemeDetailed.topFees)
              }
              if (this.chargingSchemeDetailed.detailed[i].cost === '01') {
                this.chargingSchemeDetailed.detailed[i].ele_price = Number(this.chargingSchemeDetailed.peakCost) + Number(this.chargingSchemeDetailed.peakFees)
              }
              if (this.chargingSchemeDetailed.detailed[i].cost === '02') {
                this.chargingSchemeDetailed.detailed[i].ele_price = Number(this.chargingSchemeDetailed.flatCost) + Number(this.chargingSchemeDetailed.flatFees)
              }
              if (this.chargingSchemeDetailed.detailed[i].cost === '03') {
                this.chargingSchemeDetailed.detailed[i].ele_price = Number(this.chargingSchemeDetailed.lowCost) + Number(this.chargingSchemeDetailed.lowFees)
              }
            }
          }
          this.form.schemeDetailed = JSON.stringify(this.chargingSchemeDetailed)
          if (this.form.chargingSchemeId != null) {
            updateScheme(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addScheme(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const chargingSchemeIds = row.chargingSchemeId || this.ids;
      this.$modal.confirm('是否确认删除充电规则编号为"' + chargingSchemeIds + '"的数据项？').then(function() {
        return delScheme(chargingSchemeIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/scheme/export', {
        ...this.queryParams
      }, `scheme_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
